import { useCallback, useEffect, useState } from "react"
import { ViewStyle, Platform } from "react-native"
import { router, useFocusEffect, useLocalSearchParams } from "expo-router"
import * as Burnt from "burnt"
import { debounce } from "lodash"
import {
  useIAP,
  purchaseUpdatedListener,
  purchaseErrorListener,
  finishTransaction,
} from "react-native-iap"
import * as RNLocalize from "react-native-localize"

import { Screen } from "@/components"
import AuthCodeModal from "@/components/dedicated/PayModal/AuthCodeModal"
import ChargeContent from "@/components/dedicated/PayModal/ChargeContent"
import { translate } from "@/i18n"
import { useStores } from "@/models"
import { Product } from "@/models/Order"
import { getProducts } from "@/services/api/order"
import { useAppTheme } from "@/theme/context"
import { handlePayment, splitByIntl } from "@/utils/payment"
import { useHeader } from "@/utils/useHeader"

const PayModal = () => {
  const params: any = useLocalSearchParams()
  const { theme } = useAppTheme()
  const { userStore, systemStore, productStore } = useStores()
  const [coinProducts, setCoinProducts] = useState<any>([])
  const { connected, fetchProducts, products, subscriptions, requestPurchase } = useIAP()
  const [giftModalVisible, setGiftModalVisible] = useState<boolean>(false)
  const [giftCdkText, setGiftCdkText] = useState<string>("")

  // const products = productStore.products

  let orderData
  try {
    orderData = params.data ? JSON.parse(params.data) : null
  } catch {
    console.error("Error parsing orderData:", params.orderData)
    orderData = null
  }

  useHeader({
    titleTx: "pay:vipCharge",
    leftIcon: "back",
    // leftIconColor: theme.colors.palette.gold,
    onLeftPress: () => router.back(),
    // backgroundColor: theme.colors.backgroundReverse,
    titleStyle: {
      // color: theme.colors.palette.gold,
    },
  })

  useEffect(() => {
    console.log("pay modal product change:", products)
  }, [products])

  useEffect(() => {
    getProductList()
  }, [])

  useEffect(() => {
    console.log("iap connect:", connected)
    if (!connected) {
      return
    }

    let productsSkus: any

    /*try {
      productsSkus = JSON.parse(configStore.getConfigById("pixelBirdProductsSku"))
      console.log("从配置获取的SKUs:", productsSkus)
    } catch (err) {
      console.error("pixelBirdProductsSku Parse Error: ", err)
    }*/

    if (!products || products.length === 0) {
      const defaultSkus = ["octopus_base_package_1"]
      const skusToUse = productsSkus || defaultSkus
      console.log("准备获取IAP产品，SKUs:", skusToUse)

      productStore.setLoading(true)

      fetchProducts({
        skus: skusToUse,
        type: "in-app",
      })
        .then((res) => {
          console.log("获取商品成功！", res)
          productStore.setLoading(false)
        })
        .catch((err) => {
          console.error("获取商品失败！", err)
          productStore.setLoading(false)
        })
    } else {
      console.log("已有IAP产品，跳过获取")
      if (products.length) {
        productStore.setProducts(products)
        productStore.setLoading(false)
      }
    }
  }, [connected])

  function getProductList() {
    getProducts({ type: "coin" })
      .then((res) => {
        const _products = res.data?.data?.products.map((item: Product) => {
          const iapItem = products?.find((iap) => iap.productId === item.appleSku)
          if (iapItem) {
            item.localizedPriceUnit = iapItem.currency // e.g. "¥"
            item.localizedPrice = iapItem.price // e.g. "1,300"
          } else {
            // 根据地区设置货币单位
            const locales = RNLocalize.getLocales()
            const isChina = locales[0].countryCode === "CN"

            if (isChina) {
              item.localizedPriceUnit = "¥"
            }

            item.localizedPrice = item.price?.toString() || "0"
          }

          return item
        })
        setCoinProducts(_products)
      })
      .catch((err) => {
        console.log("err!!", err)
      })
  }

  const onClose = () => {
    // router.back()
  }

  const paySuccess = (successItem: any) => {
    const { isGiftOrder, cdkText } = successItem || {}

    if (isGiftOrder && cdkText) {
      console.log("paySuccess", successItem, isGiftOrder, cdkText)
      setGiftCdkText(cdkText)
      setGiftModalVisible(true)
    } else {
      Burnt.alert({
        title: translate("pay:purchaseSuccess"),
        preset: "done",
        duration: 1,
      })
      // userStore.getUserInfo()
      // userStore.checkLogin()
    }
  }

  const pay = debounce(
    async (product: any) => {
      await handlePayment({
        selectedProduct: product,
        userStore,
        systemStore,
        router,
        paySuccess,
        onClose,
        subscriptions,
        products,
        fetchProducts,
        requestPurchase,
      })
    },
    1000,
    { leading: true, trailing: false },
  )

  return (
    <Screen style={$payModal}>
      <ChargeContent coinProducts={coinProducts} payAction={pay} orderData={orderData} />
      <AuthCodeModal
        show={giftModalVisible}
        title={translate("pay:copyCdkTitle") || "请复制兑换码"}
        isNumber={false}
        copyText={true}
        copyContent={giftCdkText}
        onConfirm={() => {
          setGiftModalVisible(false)
          Burnt.toast({
            title: translate("pay:copySuccess"),
            from: "top",
            duration: 1,
          })
        }}
        onCancel={() => setGiftModalVisible(false)}
      />
    </Screen>
  )
}

const $payModal: ViewStyle = {
  flex: 1,
}

export default PayModal
